package com.ethan.crm.service.impl;

import com.ethan.crm.domain.Permission;
import com.ethan.crm.domain.Role;
import com.ethan.crm.mapper.RoleMapper;
import com.ethan.crm.mapper.RoleMapper;
import com.ethan.crm.page.PageResult;
import com.ethan.crm.query.BaseQueryObject;
import com.ethan.crm.service.IRoleService;
import com.ethan.crm.service.IRoleService;
import com.ethan.crm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleDao;

    @Override
    public int deleteByPrimaryKey(Long id) {
        // 根据rid先删除role_permission的信息
        roleDao.deletePermissionsByRid(id);
        // 删除role信息
        int effectedCount = roleDao.deleteByPrimaryKey(id);
        return effectedCount;
    }

    @Override
    public int insert(Role record) {
        int insert = roleDao.insert(record);
        List<Permission> permissionList = record.getPermissionList();
        for (Permission permission : permissionList) {
            roleDao.insertRelation(record.getId(),permission.getId());
        }
        return insert;
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        return roleDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> selectAll() {
        return roleDao.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Role record) {
        int effectCount = roleDao.updateByPrimaryKey(record);
        //删除该角色之前的权限
        roleDao.deletePermissionsByRid(record.getId());
        //重新新增该角色的权限
        for (Permission permission : record.getPermissionList()) {
            roleDao.insertRelation(record.getId(),permission.getId());
        }
        return effectCount;
    }

    @Override
    public PageResult queryForPage(BaseQueryObject qo) {
        Long total = roleDao.queryForPageCount(qo);
        if (total == 0){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Role> RoleList = roleDao.queryForPage(qo);
        return new PageResult(total.intValue(), RoleList);
    }

    @Override
    public List<Long> queryRolesByEid(Long eid) {
        return roleDao.queryRolesByEid(eid);
    }


}
